package com.mk.mvu.book.controller;

import com.mk.mvu.book.entity.Book;
import com.mk.mvu.book.mapper.BookMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @ClassName BookController
 * @Description TODO
 * @Author admin
 * @Date 2020/8/12 16:01
 * @Version 1.0
 */
@RestController
@RequestMapping("/book")
public class BookController
{
    @Autowired
    BookMapper bookMapper;

    /**
     * 查询所有
     * @return
     */
    @GetMapping("/findAll")
    public List<Book> queryAllBook(){
        return bookMapper.findAll();
    }

    /**
     * 分页查询
     * @param page 从0开始...
     * @param size
     */
    @GetMapping("/findByPage/{page}/{size}")
    public Page<Book> queryBooks(@PathVariable("page")Integer page, @PathVariable("size")Integer size){
        PageRequest pageRequest = PageRequest.of(page,size);
        return bookMapper.findAll(pageRequest);
    }

    @PostMapping("/save")
    public String save(@RequestBody Book book){
        Book result = bookMapper.save(book);
        if(result != null){
            return "success";
        }else{
            return "error";
        }
    }

    @GetMapping("/findById/{id}")
    public Book findById(@PathVariable("id") Integer id){
        return bookMapper.findById(id).get();
    }

    @PutMapping("/update")
    public String update(@RequestBody Book book){
        Book result = bookMapper.save(book);
        if(result != null){
            return "success";
        }else{
            return "error";
        }
    }

    @DeleteMapping("/deleteById/{id}")
    public void deleteById(@PathVariable("id") Integer id){
        bookMapper.deleteById(id);
    }


}
